package ru.amse.tsyganov.jumleditor.view;

import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;

import ru.amse.tsyganov.jumleditor.commands.Command;
import ru.amse.tsyganov.jumleditor.commands.CommandFactory;
import ru.amse.tsyganov.jumleditor.model.ActivityGraph;
import ru.amse.tsyganov.jumleditor.model.State;
import ru.amse.tsyganov.jumleditor.model.StateVertex;
import ru.amse.tsyganov.jumleditor.model.Transition;

public abstract class TransitionActivePoint extends ActivePoint {
	
	private final boolean sourceMoving;
	
	public TransitionActivePoint(boolean sourceMoving) {
		this.sourceMoving = sourceMoving;
	}
	
	public abstract Transition getModel();
	
	public abstract ActivityGraphView<? extends ActivityGraph> getContainer();
	
	@Override
	public final Cursor getCursor() {
		return Cursors.getCursorSizeAll();
	}

	@Override
	public final void paintTempResult(GC gc) {
		assert gc != null;
		
		gc.setForeground(Colors.getGrayColor());
		gc.setBackground(Colors.getGrayColor());
		
		State state = (sourceMoving) ? 
				getModel().getTarget().getContainer() :
					getModel().getSource().getContainer();
		
		Point tempPoint = new Point(
				getTemporaryActivePointX(), 
				getTemporaryActivePointY());		
		
		Point connectionPoint = getContainer().getModelViewMap().
			getStatesMap().get(state).getConnectionPoint(tempPoint, sourceMoving);
		
		Line line = new Line(tempPoint.x, tempPoint.y, 
				connectionPoint.x, connectionPoint.y);
		TransitionDraughtsman.drawArrowedLine(gc, 
				line, sourceMoving);
	}

	@Override
	public final Command createCommandForAction() {
		StateView<? extends State> newStateView = 
			getContainer().getStateView( 
					getTemporaryActivePointX(), 
					getTemporaryActivePointY());
		
		if (newStateView == null) {
			return null;
		}
		
		StateVertex newSourceVertex = (sourceMoving) ? 
				newStateView.getModel().getStateVertex() :
					getModel().getSource();
				
		StateVertex newTargetVertex = (!sourceMoving) ? 
				newStateView.getModel().getStateVertex() :
					getModel().getTarget();
				
		if (newTargetVertex == newSourceVertex) {
			return null;
		}
				
		if (newSourceVertex == getModel().getSource() &&
				newTargetVertex == getModel().getTarget()) {
			
			return null;
		}
		
		TransitionView<? extends Transition> transitionView = 
			getContainer().getModelViewMap().getTransitionsMap().get(getModel());
		
		return CommandFactory.createMoveTransitionCommand(
				transitionView, 
				newSourceVertex, newTargetVertex);
	}

}
